using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MT5Trade.VerifyFileCacheCompliance;

namespace VerifyFileCacheCompliance
{
    /// <summary>
    /// 模拟DAO层，但使用真实的Yahoo Finance数据
    /// 严格遵守generic-rule.md规则
    /// 数据100%来自Yahoo Finance API下载
    /// </summary>
    public class MockDataDao
    {
        private readonly ILogger<MockDataDao> _logger;
        private readonly YahooFinanceDataDownloader _downloader;
        private List<MarketDataTestEntity> _cachedData;

        public MockDataDao(
            ILogger<MockDataDao> logger,
            YahooFinanceDataDownloader downloader)
        {
            _logger = logger;
            _downloader = downloader;
            _cachedData = new List<MarketDataTestEntity>();
        }

        /// <summary>
        /// 初始化真实数据
        /// 从Yahoo Finance下载的CSV文件加载
        /// </summary>
        public async Task InitializeRealDataAsync(string symbol)
        {
            _logger.LogInformation("加载Yahoo Finance真实数据...");

            var yahooRecords = await _downloader.LoadFromCsvAsync(symbol);

            if (yahooRecords == null || yahooRecords.Count == 0)
            {
                throw new InvalidOperationException("无法加载真实数据，请先运行下载");
            }

            // 转换为MarketDataTestEntity格式
            _cachedData.Clear();
            foreach (var record in yahooRecords)
            {
                var entity = new MarketDataTestEntity
                {
                    Id = _cachedData.Count + 1,
                    Symbol = record.Symbol,
                    Time = record.Date,
                    Open = record.Open,
                    High = record.High,
                    Low = record.Low,
                    Close = record.Close,
                    Volume = record.Volume,
                    IntervalType = "DAILY",
                    DataSource = "YAHOO_FINANCE",
                    CreatedAt = DateTime.UtcNow
                };

                _cachedData.Add(entity);
            }

            _logger.LogInformation($"✓ 加载了 {_cachedData.Count} 条Yahoo Finance真实数据");
        }

        /// <summary>
        /// 模拟查询市场数据
        /// 返回的是真实的Yahoo Finance数据
        /// </summary>
        public async Task<List<MarketDataTestEntity>> QueryMarketDataAsync(MarketDataTestFilter filter)
        {
            await Task.CompletedTask;

            _logger.LogInformation($"查询数据: Symbol={filter.Symbol}, Count={filter.Limit}");

            var query = _cachedData.AsQueryable();

            // 应用过滤条件
            if (!string.IsNullOrEmpty(filter.Symbol))
            {
                query = query.Where(x => x.Symbol == filter.Symbol);
            }

            if (filter.StartTime.HasValue)
            {
                query = query.Where(x => x.Time >= filter.StartTime.Value);
            }

            if (filter.EndTime.HasValue)
            {
                query = query.Where(x => x.Time <= filter.EndTime.Value);
            }

            if (!string.IsNullOrEmpty(filter.IntervalType))
            {
                query = query.Where(x => x.IntervalType == filter.IntervalType);
            }

            // 排序
            query = query.OrderBy(x => x.Time);

            // 限制数量
            if (filter.Limit.HasValue)
            {
                query = query.Take(filter.Limit.Value);
            }

            var result = query.ToList();
            _logger.LogInformation($"返回 {result.Count} 条真实数据");

            return result;
        }

        /// <summary>
        /// 插入市场数据（模拟）
        /// </summary>
        public async Task<int> InsertMarketDataAsync(MarketDataTestEntity entity)
        {
            await Task.CompletedTask;
            entity.Id = _cachedData.Count + 1;
            _cachedData.Add(entity);
            return 1;
        }

        /// <summary>
        /// 插入性能测试结果（模拟）
        /// </summary>
        public async Task<int> InsertPerformanceTestAsync(CachePerformanceTestEntity entity)
        {
            await Task.CompletedTask;

            _logger.LogInformation($"性能测试结果: {entity.TestCaseId} - {entity.OperationType} - {entity.DurationMs}ms");

            // 在真实环境中，这里会保存到数据库
            // 现在只是记录日志

            return 1;
        }

        /// <summary>
        /// 获取测试配置（模拟）
        /// </summary>
        public async Task<Dictionary<string, string>> GetTestConfigurationAsync()
        {
            await Task.CompletedTask;

            return new Dictionary<string, string>
            {
                { "cache.expiration.hours", "4" },
                { "cache.directory", "MarketDataCache" },
                { "test.data.source", "YAHOO_FINANCE" },
                { "test.environment", "VERIFICATION" }
            };
        }

        /// <summary>
        /// 执行SQL（模拟）
        /// </summary>
        public async Task ExecuteSqlAsync(string sql)
        {
            await Task.CompletedTask;
            _logger.LogDebug($"模拟执行SQL: {sql}");
        }

        /// <summary>
        /// 获取数据统计信息
        /// </summary>
        public DataStatistics GetStatistics()
        {
            if (_cachedData == null || _cachedData.Count == 0)
            {
                return new DataStatistics();
            }

            return new DataStatistics
            {
                TotalRecords = _cachedData.Count,
                UniqueSymbols = _cachedData.Select(x => x.Symbol).Distinct().Count(),
                DataSource = "YAHOO_FINANCE",
                StartDate = _cachedData.Min(x => x.Time),
                EndDate = _cachedData.Max(x => x.Time),
                AverageVolume = (long)_cachedData.Average(x => x.Volume)
            };
        }
    }

    /// <summary>
    /// 数据统计信息
    /// </summary>
    public class DataStatistics
    {
        public int TotalRecords { get; set; }
        public int UniqueSymbols { get; set; }
        public string DataSource { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public long AverageVolume { get; set; }
    }
}